# addr1 = ('192.168.3.14', 8081)需改成server端nano的地址addr1 = ('192.168.3.14', 8081)
import pickle
import socket
import numpy as np
from utils_qt.mianwindow_function import *
from threading import Thread
from utils_drawbox.my_utils import draw_bbox

class Client():
    def __init__(self,addr):
        self.addr = addr
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.message_bytes = b''

    # 解决粘包和半包
    def receive_message(self, count):
        # 确保字节收够了(当self.message_bytes的长度<要求的接收数count,继续接收)
        while len(self.message_bytes) < count:
            data = self.socket.recv(count)
            if not data:
                continue
            self.message_bytes += data
        # 防止多收，只取出需要的字节数量
        message = self.message_bytes[:count]
        # 清除这部分return的字节
        self.message_bytes = self.message_bytes[count:]
        return message


    def receive_and_update(self, flag):
        # 等待按下“start”按钮
        while True:
            if ui.init_flag:
                break
        self.socket.connect(self.addr)                                         # 连接服务器
        # 接收图像并显示
        while True:
            # start = time.time()
            # 获取消息长度
            msg_size = self.receive_message(16).decode()
            rece_msg = self.receive_message(int(msg_size))
            rece_frame, result = pickle.loads(rece_msg)
            # rece_frame = self.socket.recv(96100)
            # 转换数据格式成uint8
            rece_frame = np.frombuffer(rece_frame, dtype='uint8')
            # 解码ndarray成img
            decoded_frame = cv2.imdecode(rece_frame, 1)

            # 更新QT界面全景窗口
            ui.update_img(img=decoded_frame, label_name="WholeScene", flag=flag)  # update全景窗口

            # if type(decoded_frame) == np.ndarray:     # 预防解码失败

            # 更新QT界面检测窗口
            draw_bbox(imgs=decoded_frame, results=result, draw_label=True, line_thickness=3)
            ui.update_img(img=decoded_frame, label_name="DetectedResults", flag=flag)       # update

            # cv2.putText(decoded_frame, "client", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
            # cv2.imshow('frame{}'.format(flag), decoded_frame)
            # # print(flag,decoded_frame.size)
            # if cv2.waitKey(1) == 27:
            #     break

            # use_time = time.time() - start
            # print("\rfps:", 1/use_time, end="")

        self.socket.close()

if __name__ == "__main__":
    # qt实例化
    app = QApplication(sys.argv)
    ui = UiMain()

    # 放nano上，需改成server端nano的地址addr1 = ('192.168.3.14', 8081)
    # TCP线程1
    # addr1 = ('192.168.1.113', 8081)       # addr1 = ('192.168.43.22', 8081)
    addr1 = ('10.147.19.141', 8081)       # nano zerotier
    # addr1 = ('192.168.3.44', 8081)       # addr1 = ('192.168.43.22', 8081)
    client_socket1 = Client(addr1)
    th1 = Thread(target=client_socket1.receive_and_update, args="1")
    th1.setDaemon(True)
    th1.start()
    # TCP线程2
    # addr2 = ('192.168.3.14', 8082)       # addr2 = ('192.168.43.22', 8082)
    # client_socket1 = Client(addr2)
    # th2 = Thread(target=client_socket1.receive_and_update, args="2")
    # th2.setDaemon(True)
    # th2.start()

    # QT主线程
    ui.show()
    sys.exit(app.exec_())




